package com.ian.departmentmanager.mvc;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.ian.departmentmanager.bo.Member;
import com.ian.departmentmanager.service.MailService;
import com.ian.departmentmanager.service.MemberService;

@Controller
public class MessSendController {

	private MailService mailService;

	@Autowired
	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}
	
	private MemberService memberService;

	@Autowired
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	@RequestMapping(value = "/message/editMail.htm", method = RequestMethod.GET)
	protected ModelAndView editMail() {
		ModelAndView mav = new ModelAndView("editMail");
		List<Member> members = memberService.getMembers();
		mav.addObject("members", members);
		return mav;
	}

	@RequestMapping(value = "/message/sendMail.htm", method = RequestMethod.POST)
	protected ModelAndView sendMail(
			@RequestParam(value = "sendFrom") String sendFrom,
			@RequestParam(value = "sendTo") String sendTo,
			@RequestParam(value = "title") String title,
			@RequestParam(value = "attachFile") String attachFile,
			@RequestParam(value = "content") String content,
			HttpServletRequest request) {

		String a[] = sendTo.split(",");
		List<String> mailResults = new ArrayList<String>();
		if (attachFile.equals("")) {
			for (int i = 0; i < a.length; i++) {
				String sendResult = mailService.sendMail(sendFrom, a[i], title,
						content);
				mailResults.add(a[i]+sendResult);
			}
		} else {
			for (int i = 0; i < a.length; i++) {
				String sendResult = mailService.sendMail(sendFrom, a[i], title,
						attachFile, content);
				mailResults.add(a[i]+sendResult);
			}
		}
		ModelAndView mav = new ModelAndView("mailResult");
		mav.addObject("mailResults", mailResults);
		return mav;
	}

}
